package com.xlserver.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xlserver.dao.*;
import com.xlserver.domain.Consultation;
import com.xlserver.domain.Message;
import com.xlserver.domain.Photo;
import com.xlserver.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class MessageService {
    @Autowired
    MessageMapper messageMapper;

    @Autowired
    PhotoMapper photoMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    ConsultationMapper consultationMapper;

    @Autowired
    TimeUtil timeUtil;

    @Autowired
    CounselorMapper counselorMapper;

    @Autowired
    SupervisorMapper supervisorMapper;

    public static Map<String,List<String>> waitingUsers;
    /**
     * 建立会话
     */
    public JSONArray createChat(int uid,int cid){
        if(getHid(uid,cid) == -1){
            consultationMapper.insert(new Consultation(uid,cid));
        }
        //获取建立的会话的hid
//        int hid = Objects.requireNonNull(consultationMapper.selectList(
//                        new QueryWrapper<Consultation>().eq("uid", uid).eq("cid", cid))
//                .stream().max(Comparator.comparingInt(Consultation::getHid)).orElse(null)).getHid();
//        System.out.println("hid:"+hid);
//        JSONObject chatId = new JSONObject();
//        chatId.put("hid",hid);
        //获取历史记录
        return getHistory(uid,cid);
    }

    /**
     * 返回当前uid与cid对应会话的hid，若无正在进行的会话，返回-1
     */
    public int getHid(int uid,int cid){
        List<Consultation> hid = consultationMapper.selectList(new QueryWrapper<Consultation>()
                .eq("cid",cid)
                .eq("uid",uid)).stream()
                .filter(consultation -> Objects.equals(consultation.getBeginTime(), consultation.getEndTime()))
                .collect(Collectors.toList());
        return hid.size() == 0 ? -1 : hid.get(0).getHid();
    }

    /**
     *获取文本消息
     */
    public JSONArray getMessages(int sender, int receiver) {
        QueryWrapper<Message> queryMsg = new QueryWrapper<>();
        queryMsg.eq("hSenderId", sender)
                .eq("hReceiverId", receiver).orderBy(true,true,"hTextTime");
        JSONArray ret = new JSONArray();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        messageMapper.selectList(queryMsg).forEach((msg)->{
            JSONObject obj = new JSONObject();
//            obj.put("key",0);
            obj.put("message", msg.getMsg());
            obj.put("from", msg.getSenderId());
            obj.put("to", msg.getReceiverId());
            obj.put("time", ft.format(msg.getTime()));
            if (msg.getSign() == 0){
                obj.put("type",0);
            }
            else {
                obj.put("type",2);
            }
            ret.add(obj);
        });
        return ret;
    }
    /**
     *获取某次会话的文本消息
     */
    public JSONArray getMessages(int sender, int receiver,int hid) {
        QueryWrapper<Message> queryMsg = new QueryWrapper<>();
        queryMsg.eq("hSenderId", sender)
                .eq("hReceiverId", receiver)
                .eq("hid",hid)
                .orderBy(true,true,"hTextTime");
        JSONArray ret = new JSONArray();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        messageMapper.selectList(queryMsg).forEach((msg)->{
            JSONObject obj = new JSONObject();
            obj.put("message", msg.getMsg());
            obj.put("from", msg.getSenderId());
            obj.put("to", msg.getReceiverId());
            obj.put("time", ft.format(msg.getTime()));
            if (msg.getSign() == 0){
                obj.put("type",0);
            }
            else {
                obj.put("type",2);
            }
            ret.add(obj);
        });
        return ret;
    }

    /**
     *获取图片消息
     */
    public JSONArray getPhotos(int sender, int receiver) {
        QueryWrapper<Photo> queryPhoto = new QueryWrapper<>();
        queryPhoto.eq("hSenderId", sender)
                .eq("hReceiverId", receiver).orderBy(true,true,"hPhotoTime");
        JSONArray ret = new JSONArray();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        photoMapper.selectList(queryPhoto).forEach((photo)->{
            JSONObject obj = new JSONObject();
//            obj.put("key",0);
            obj.put("message", photo.getPhoto());
            obj.put("from", photo.getSenderId());
            obj.put("to", photo.getReceiverId());
            obj.put("time", ft.format(photo.getTime()));
            obj.put("type",1);
            ret.add(obj);
        });
        return ret;
    }
    /**
     *获取某次会话的图片消息
     */
    public JSONArray getPhotos(int sender, int receiver,int hid) {
        QueryWrapper<Photo> queryPhoto = new QueryWrapper<>();
        queryPhoto.eq("hSenderId", sender)
                .eq("hReceiverId", receiver)
                .eq("hid",hid)
                .orderBy(true,true,"hPhotoTime");
        JSONArray ret = new JSONArray();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        photoMapper.selectList(queryPhoto).forEach((photo)->{
            JSONObject obj = new JSONObject();
            obj.put("message", photo.getPhoto());
            obj.put("from", photo.getSenderId());
            obj.put("to", photo.getReceiverId());
            obj.put("time", ft.format(photo.getTime()));
            obj.put("type",1);
            ret.add(obj);
        });
        return ret;
    }

    /**
     *获取历史记录
     */
    public JSONArray getHistory(int sender, int receiver) {
        JSONArray res = new JSONArray();
        res.addAll(getMessages(sender, receiver));
        res.addAll(getPhotos(sender,receiver));
        res.addAll(getMessages(receiver, sender));
        res.addAll(getPhotos(receiver,sender));
        res.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("time")));
        return res;
    }
    /**
     *获取某次会话的历史记录
     */
    public JSONArray getHistory(int sender, int receiver,int hid) {
        JSONArray res = new JSONArray();
        res.addAll(getMessages(sender, receiver,hid));
        res.addAll(getPhotos(sender,receiver,hid));
        res.addAll(getMessages(receiver, sender,hid));
        res.addAll(getPhotos(receiver,sender,hid));
        res.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("time")));
        return res;
    }

    /**
     * 获取咨询日期，咨询评分，咨询时长，咨询师name
     */
    public JSONArray getUserHistory(int userId){
        JSONArray res = new JSONArray();
        consultationMapper.selectList(new QueryWrapper<Consultation>().eq("uid",userId)).forEach(
                consultation -> {
                    System.out.println(consultation+"++++++");
                    if(photoMapper.selectList(new QueryWrapper<Photo>().eq("hid",consultation.getHid())).size() != 0 ||
                            messageMapper.selectList(new QueryWrapper<Message>().eq("hid",consultation.getHid())).size() != 0){
                        JSONObject obj = new JSONObject();
                        obj.put("date",consultation.getEndTime());
                        try {
                            obj.put("time",timeUtil.getTimeDiff(consultation));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        obj.put("rank",consultation.getCrank());
                        obj.put("cName",counselorMapper.selectById(consultation.getCid()).getName());
                        obj.put("hid",consultation.getHid());
                        obj.put("avatar",counselorMapper.selectById(consultation.getCid()).getProfilePhoto());
                        res.add(obj);
                    }
                }
        );
        return res;
    }
    /**
     * 根据hid获取会话时间与咨询师姓名
     */
    public JSONObject getInfoByHid(int hid) throws ParseException {
        JSONObject ret = new JSONObject();
        Consultation consultation = consultationMapper.selectById(hid);
        ret.put("name",counselorMapper.selectById(consultation.getCid()).getName());
        ret.put("time", consultation.getBeginTime());
        return ret;
    }
    /**
     * 参数：访客id，咨询师姓名
     * 响应：访客头像，咨询师姓名，咨询师头像，时间，内容
     */
    public JSONArray getMsgsOfChat(int hid){
        JSONArray res = new JSONArray();
        Consultation consultation = consultationMapper.selectById(hid);
        if (consultation == null){
            return res;
        }
        int uid = consultation.getUid();
        int cid = consultation.getCid();
        res.add(getHistory(uid,cid,hid));
        JSONObject info = new JSONObject();
        if(uid<20000 && uid>10000){
            info.put("uAvatar",userMapper.selectById(uid).getProfilePhoto());
            info.put("uName",userMapper.selectById(uid).getUsername());
        }
        else if (uid>20000 && uid<30000){
            info.put("uAvatar",counselorMapper.selectById(uid).getProfilePhoto());
            info.put("uName",counselorMapper.selectById(uid).getName());
        }

        res.add(info);
        return res;
    }
    /**
     * 获取当前所有咨询师进行的会话数量
     */
    public JSONObject getSumOfChat(){
        JSONObject ret = new JSONObject();
        ret.put("sum",consultationMapper.selectCount(new QueryWrapper<Consultation>()
                        .apply("cid <= 30000 and cid >= 20000")
                        .apply("h_beginTime = h_endTime")));
        return ret;
    }
    /**
     * 获取当前所有督导进行的会话数量
     */
    public JSONObject getSumOfSuperChat(){
        JSONObject ret = new JSONObject();
        ret.put("sum",consultationMapper.selectCount(new QueryWrapper<Consultation>()
                .apply("cid >= 30000")
                .apply("h_beginTime = h_endTime")));
        return ret;
    }
    /**
     * 获取当前督导正在进行的会话数
     */
    public JSONObject getSumOfChats(int id){
        JSONObject ret = new JSONObject();
        ret.put("sum",consultationMapper.selectCount(new QueryWrapper<Consultation>()
                .apply("cid >= 30000")
                .apply("h_beginTime = h_endTime")));
        return ret;
    }

    /**
     *插入文本信息
     */
    public void insertMsg(String message, int sender, int receiver, int hid) {
        messageMapper.insert(new Message(sender, receiver, hid, message));
    }
    /**
     * 插入消息中转发的历史记录，存入hid
     */
    public void insertHistory(String message, int sender, int receiver, int hid) {
        messageMapper.insert(new Message(hid, sender, receiver, message,1));
    }

    /**
     *插入图片信息
     */
    public void insertPhoto(String photo, int sender, int receiver, int hid) {
        photoMapper.insert(new Photo(sender, receiver, hid, photo));
    }
    /**
     * 结束会话
     */
    public void closeChat(int hid){
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        consultationMapper.update(null,new UpdateWrapper<Consultation>()
                .eq("hid",hid)
                .set("h_endTime",timestamp));
    }
    /**
     * 根据cid获取正在进行的会话内容
     */
    public JSONArray getOnGoingChat(int cid){
        AtomicReference<JSONArray> res = new AtomicReference<>(new JSONArray());
        consultationMapper.selectList(new QueryWrapper<Consultation>()
                .eq("cid",cid)
                .apply("h_beginTime = h_endTime"))
                .forEach(consultation -> {
                    if (photoMapper.selectList(new QueryWrapper<Photo>().eq("hid",consultation.getHid())).size() != 0 ||
                    messageMapper.selectList(new QueryWrapper<Message>().eq("hid",consultation.getHid())).size() != 0){
                        res.set(getHistory(consultation.getCid(), consultation.getUid(), consultation.getHid()));
                    }
                });
        return res.get();
    }

}
